<template>
  <!--申请后结算-->
  <el-dialog
    custom-class="settlement-pop"
    title="申请后结算"
    :visible.sync="dialogVisible17"
    width="800px">
    <div style="max-height:500px;overflow-y: auto" class="settlement-div">
      <el-form :model="form" size="mini" label-width="120px" :rules="rules" ref="form">
          <div class="goods-item" v-for="(item,index) in form.list" :key="index">
             <div class="item-top">
                <div class="name">{{ item.goodsName }}/{{ item.goodsSn }} <span style="color:red;">/ 可申请结算数量：{{ item.canApplyNum }}</span></div>
                <el-button round type="primary" plain size='mini' style="margin-top:-20px;float:right;padding:5px 15px" @click="addItem(index)">新增</el-button>
             </div>
             <div class="item-con">
               <el-table :data="item.goodsList" size="mini" border style="width: 100%;margin:12px 0">
                 <el-table-column
                   label="#"
                   align="center"
                   type="index"
                   width="50">
                 </el-table-column>
                 <el-table-column
                   align="center"
                   label="本次结算数量"
                   min-width="100">
                   <template slot-scope="scope">
                     <el-form-item :prop="`list.${index}.goodsList.${scope.$index}.applyNum`" :rules="applyNumValidate(index,scope.$index)" label-width="0px">
                       <el-input v-model="scope.row.applyNum" style="width:100%" type="number" size="mini"></el-input>
                     </el-form-item>
                   </template>
                 </el-table-column>
                 <el-table-column
                   label="本次结算单价"
                   min-width="100"
                   align="center">
                   <template slot-scope="scope">
                     <el-form-item  :prop="`list.${index}.goodsList.${scope.$index}.applyPrice`" :rules="rules.applyPrice" label-width="0px">
                       <el-input v-model="scope.row.applyPrice" style="width:100%"  type="number" size="mini"></el-input>
                     </el-form-item>
                   </template>
                 </el-table-column>
                 <el-table-column
                   label="结算吨毛利"
                   min-width="100"
                   align="center">
                   <template slot-scope="scope">
                     {{scope.row | fifProfit(item)}}
                   </template>
                 </el-table-column>
                 <el-table-column
                   label="采销盈亏占比"
                   min-width="180"
                   align="center">
                   <template slot-scope="scope">
                      销售：{{ (item.settleSaleProfitRate*100).toFixed(0) }}% / 采购：{{ (item.settlePurchaseProfitRate*100).toFixed(0) }}%
                   </template>
                 </el-table-column>
                 <el-table-column
                   label="销售预估吨毛利"
                   min-width="120"
                   align="center">
                   <template slot-scope="scope">
                     <el-form-item style="margin-bottom: 0;"  label-width="0px">
                         {{scope.row | fifProfit(item,'settleSaleProfitRate')}}
                     </el-form-item>
                   </template>
                 </el-table-column>
                 <el-table-column label="采购预估吨毛利" min-width="120" align="center">
                   <template slot-scope="scope">
                     <el-form-item style="margin-bottom: 0;" label-width="0px">
                       {{scope.row | fifProfit(item,'settlePurchaseProfitRate')}}
                     </el-form-item>
                   </template>
                 </el-table-column>
                 <el-table-column  label="备注" min-width="150" align="center">
                   <template slot-scope="scope">
                     <el-form-item style="margin-bottom: 0;" label-width="0px">
                       <el-input v-model="scope.row.remark"></el-input>
                     </el-form-item>
                   </template>
                 </el-table-column>

                 <el-table-column  label="操作" width="100" align="center" fixed="right">
                   <template slot-scope="scope">
                     <el-button type="text" size="mini" @click="delGoods(index,scope.$index)">删除</el-button>
                   </template>
                 </el-table-column>
               </el-table>
             </div>
          </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose17">取 消</el-button>
        <el-button type="primary" @click="handleConfirm17" :loading="btnLoading17">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {delaySettleOrderInfo,delaySettleApply} from '@/api/order'
import {goodsLineAddTracking} from '@/api/company'
import {validatePhone} from '@/utils/validate';
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'



const defeaultGoodsItem = {
  "ogId" : '',
  "applyNum" :'',
  "applyPrice" : '',
  "remark" : "",
}
const defeaultForm = {
  orderId:'',
  list : []
}
export default {
  name: "postSettlement",
  data(){
    const validateapplyNum = (rule, value, callback) => {
    };
    return {
      form:JSON.parse(JSON.stringify(defeaultForm)),
      dialogVisible17:false,
      btnLoading17:false,
      rules:{
        applyPrice:[{required: true, message: '此项必填', trigger: 'blur'},],

      },
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {

  },
  created() {

  },
  filters: {
    fifProfit(ee,e,key){
      if(ee.applyPrice === ''){
        return ''
      }else{
        let profit = e.goodsPrice - ee.applyPrice - e.goodsFreight - e.consultation;
        if(key){
          return (profit*e[key]).toFixed(2)
        }else{
          return profit.toFixed(2)
        }
      }

    },
  },
  methods:{
    applyNumValidate(i,ii){
      return [
        {required: true,
          validator: (rule, value, callback)=>{
            let canApplyNum = this.form.list[i].canApplyNum
            let sum = 0
            this.form.list[i].goodsList.forEach((item,index)=>{
                sum += item.applyNum ? parseFloat(item.applyNum) : 0
            })
            if (sum > canApplyNum) {
              callback(new Error('已大于可申请数量'))
            }else if(value <= 0){
              callback(new Error('大于零的数'))
            }
            callback()
          },
          trigger: 'blur'}
      ]
    },
    addItem(index){
      let c = JSON.parse(JSON.stringify(defeaultGoodsItem));
      c.ogId = this.form.list[index].ogId
      this.form.list[index].goodsList.push(JSON.parse(JSON.stringify(c)))
    },
    delGoods(i,ii){
      this.form.list[i].goodsList.splice(ii,1)
    },
    showPop(item){
      this.dialogVisible17 = true;
      this.form = JSON.parse(JSON.stringify(defeaultForm));
      this.form.orderId = item.orderId
      this.getGoodsList(item.orderId)

    },
    getGoodsList(orderId){
      delaySettleOrderInfo({orderId:orderId}).then((res)=>{
         res.list.forEach((item)=>{
           item.goodsList = []
         })
         this.form.list = res.list
      })
    },
    //关闭弹窗
    handleClose17(){
      this.dialogVisible17 = false;
    },

    //确认
    handleConfirm17(){
      let data = {};
      data.orderId = this.form.orderId
      data.goodsList = []
      this.form.list.forEach((item)=>{
        data.goodsList = data.goodsList.concat(item.goodsList)
      })
      if(data.goodsList.length == 0){
        this.$message.error('请新增需结算的商品')
        return false
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading17 = true;

          delaySettleApply(data).then((res)=>{
            this.btnLoading17 = false;
            this.handleClose17();
            this.$emit('update')
          }).catch(()=>{
            this.btnLoading17 = false;
          })
        }
      })
    },
  },
}
</script>

<style lang="scss">
    .settlement-pop{
      .el-dialog__body {
        padding: 20px;
      }
    }
    .settlement-div{
      .goods-item{
        border-radius: 4px;
        background: #f9fcff;
        border:1px solid #e7f3ff;
        padding:5px 12px;
        margin-bottom: 20px;
        .item-top{
          padding:10px 0;
          border-bottom: 1px solid #e7f3ff;
          .name{
            font-size: 12px;
            font-weight: bold;
            color:#000
          }
        }
      }
      .goods-item:last-child{
        margin-bottom: 0;
      }
    }
</style>
